﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using vnMcdonald.Models;
using WebMatrix.WebData;
namespace vnMcdonald.Controllers
{
    public class AdminController : Controller
    {
        //
        // GET: /Admin/
        vnMcdonaldContext db = new vnMcdonaldContext();
        [Authorize(Roles = "Admin")]
        public ActionResult Index()
        {
            return RedirectToAction("categories");
        }
/*************************************************************************
 * Quan Ly Danh Muc
 *************************************************************************/
        [Authorize(Roles = "Admin")]
        public ActionResult Categories()
        {
            var cat = db.Categories;
            return View(cat);
        }

        [Authorize(Roles = "Admin")]
        public ActionResult Update_Status_Categories(int id)
        {
            var find = db.Categories.Find(id);
            if (find.IsActive == 1)
            {
                find.IsActive = 0;
            }
            else find.IsActive = 1;
            db.Entry(find).State = EntityState.Modified;
            db.SaveChanges();
            return PartialView(find);
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        public ActionResult CategoriesCreate(Category category, string txtaddcategory)
        {
            int maxOrder = db.Categories.Max(c => c.CategoryId);
            Category category_add = new Category();
            category_add.Name = txtaddcategory;
            category_add.Order = maxOrder+1;
            category_add.IsActive = 1;
            db.Entry(category_add).State = EntityState.Added;
            db.SaveChanges();
            return RedirectToAction("Categories");
            //return View(category);
        }

        [Authorize(Roles = "Admin")]
        public ActionResult CategoriesDel(int id)
        {
            Category category = db.Categories.Find(id);
            db.Categories.Remove(category);
            db.SaveChanges();
            return RedirectToAction("Categories");
        }
/*************************************************************************
* Quan Ly San Pham
*************************************************************************/

        [Authorize(Roles = "Admin")]
        public ActionResult Products(int? cid)
        {
            ViewBag.loadcategory = new SelectList(db.Categories, "CategoryId", "Name");
            if (cid == null)
            {
                var product = db.Products.Where(p => p.IsActive != 2).OrderByDescending(a => a.ProductId);
                return View(product.ToList());
            }
            else {
                var product = db.Products.Where(p => p.CategoryId == cid && p.IsActive != 2).OrderByDescending(a => a.ProductId);
                return View(product.ToList());
            }
        }

        [Authorize(Roles = "Admin")]
        //[HttpPost]
        public PartialViewResult ProductsReload(string id) 
        {
            if (id == null || id == "")
            {
                var product = db.Products.Where(p => p.IsActive != 2).OrderByDescending(a => a.ProductId);
                return PartialView(product.ToList());
            }
            else
            {
                var cid = int.Parse(id);
                var product = db.Products.Where(p => p.CategoryId == cid && p.IsActive != 2).OrderByDescending(a => a.ProductId);
                return PartialView(product.ToList());
            }
        }

        [Authorize(Roles = "Admin")]
        public ActionResult ProductCreate()
        {
            ViewBag.loadcategory = new SelectList(db.Categories, "CategoryId", "Name");
            return View();
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        public ActionResult ProductCreate(Product product, int loadcategory, IEnumerable<HttpPostedFileBase> imageproduct)
        {
            int last_productid = 0, last_imageid;
            int order = 0;
            string date = DateTime.Today.ToString("yyyy-M-d");
            Product add_product = new Product();
            add_product.Name = product.Name;
            add_product.Description = product.Description;
            add_product.Price = product.Price;
            add_product.CreateDate = Convert.ToDateTime(date);
            add_product.CategoryId = loadcategory;
            add_product.IsActive = 1;
            Boolean check = true;
            foreach (var image in imageproduct)
            {
                if (image != null && image.ContentLength > 0)
                {
                    var ext = Path.GetExtension(image.FileName);
                    ext = ext.Substring(1, ext.Length - 1);
                    ext = ext.ToLower();
                    if (ext == "jpg" || ext == "png" ||ext == "gif")
                    {
                        if (image.ContentLength <= 2*1024*1024)
                        {
                            if (check)
                            {
                                try
                                {
                                    db.Entry(add_product).State = EntityState.Added;
                                    db.SaveChanges();
                                    last_productid = db.Products.Max(p => p.ProductId);
                                    check = false;
                                }
                                catch
                                {
                                    ModelState.AddModelError("info_err", "Thêm không thành công!");
                                    ViewBag.loadcategory = new SelectList(db.Categories, "CategoryId", "Name");
                                    return View();
                                }
                                
                            }
                            if (check == false)
                            {
                                last_imageid = db.Images.Max(i => i.ImageId);
                                last_imageid = last_imageid + 1;
                                var fileName = last_imageid + "-" + Path.GetFileName(image.FileName);
                                //var fileName = Path.GetFileName(image.FileName);
                                var path = Path.Combine(Server.MapPath("~/Uploads/Products/"), fileName);
                                image.SaveAs(path);
                                Image add_image = new Image();
                                add_image.Name = fileName;
                                add_image.Src = "/Uploads/Products/" + fileName;
                                add_image.Order = order;
                                add_image.ProductId = last_productid;
                                add_image.IsActive = 1;
                                db.Entry(add_image).State = EntityState.Added;
                                db.SaveChanges();
                                order++;
                            }
                        }
                        else ModelState.AddModelError("error", "Dung lượng hình ảnh quá lớn. Dung lượng tối đa cho phép là 2M");
                        
                    }
                    else ModelState.AddModelError("error", "Hình ảnh không đúng định dạng. chỉ hổ trợ đuôi mở rộng: jpg,png,gif.");
                }
                else
                {
                    ModelState.AddModelError("error", "Hình ảnh không được bỏ trống");
                }

            }
            if (check == false)
            {
                return RedirectToAction("products");
            }
            ViewBag.loadcategory = new SelectList(db.Categories, "CategoryId", "Name");
            return View();
        }

        [Authorize(Roles = "Admin")]
        public ActionResult ProductEdit(int id = 0)
        {
            Product product = db.Products.Find(id);
            if (product == null)
            {
                return HttpNotFound();
            }
            ViewBag.loadcategory = new SelectList(db.Categories, "CategoryId", "Name", product.CategoryId);
            return View(product);
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        public ActionResult ProductEdit(Product product, int loadcategory, IEnumerable<HttpPostedFileBase> imageproduct)
        {
                int last_imageid;
                int last_order = 0;
                foreach (var image in imageproduct)
                {
                    if (image != null && image.ContentLength > 0)
                    {
                        var ext = Path.GetExtension(image.FileName);
                        ext = ext.Substring(1, ext.Length - 1);
                        ext = ext.ToLower();
                        if (ext == "jpg" || ext == "png" || ext == "gif")
                        {
                            if (image.ContentLength <= 2 * 1024 * 1024)
                            {
                                last_imageid = db.Images.Max(i => i.ImageId);
                                last_imageid = last_imageid + 1;
                                var fileName = last_imageid + "-" + Path.GetFileName(image.FileName);
                                //var fileName = Path.GetFileName(image.FileName);
                                var path = Path.Combine(Server.MapPath("~/Uploads/Products/"), fileName);
                                image.SaveAs(path);
                                int pid = product.ProductId;
                                if (db.Images.Where(p => p.ProductId == pid).Max(o => o.Order) != null)
                                {
                                    last_order = last_order + 1;
                                }
                                Image add_image = new Image();
                                add_image.Name = fileName;
                                add_image.Src = "/Uploads/Products/" + fileName;
                                add_image.Order = last_order;
                                add_image.ProductId = product.ProductId;
                                add_image.IsActive = 1;
                                db.Entry(add_image).State = EntityState.Added;
                                db.SaveChanges();
                            }
                            else
                            {
                                ModelState.AddModelError("error", "Dung lượng hình ảnh quá lớn. Dung lượng tối đa cho phép là 2M");
                                ViewBag.loadcategory = new SelectList(db.Categories, "CategoryId", "Name", product.CategoryId);
                                return View(product);
                            }
                        }
                        else {
                            ModelState.AddModelError("error", "Hình ảnh không đúng định dạng. chỉ hổ trợ đuôi mở rộng: jpg,png,gif.");
                            ViewBag.loadcategory = new SelectList(db.Categories, "CategoryId", "Name", product.CategoryId);
                            return View(product);
                        } 
                    }
                }
                product.CategoryId = loadcategory;
                db.Entry(product).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("ProductView/" + product.ProductId);
        }

        [Authorize(Roles = "Admin")]
        public ActionResult ProductView(int id = 0) 
        {
            Product product = db.Products.Find(id);
            if (product == null)
            {
                return HttpNotFound();
            }
            return View(product);
        }

        [Authorize(Roles = "Admin")]
        public ActionResult Delete_Products(int id)
        {
            var find = db.Products.Find(id);
            find.IsActive = 2;
            db.Entry(find).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Products");
        }

        [Authorize(Roles = "Admin")]
        public PartialViewResult Update_Status_Products(int id)
        {
            var find = db.Products.Find(id);
            if (find.IsActive == 1)
            {
                find.IsActive = 0;
            }
            else
            {
                find.IsActive = 1;
            }
            db.Entry(find).State = EntityState.Modified;
            db.SaveChanges();
            return PartialView(find);
        }

        [Authorize(Roles = "Admin")]
        public PartialViewResult Update_status_image(int id)
        {
            var find = db.Images.Find(id);
            if (find.IsActive == 1)
            {
                find.IsActive = 0;
                //stt = false;//"<span class='sttimg_disable sttimg'></span>";
            }
            else {
                find.IsActive = 1;
                //stt = true;//"<span class='sttimg_enable sttimg'></span>";
            }
            db.Entry(find).State = EntityState.Modified;
            db.SaveChanges();
            return PartialView(find);
        }


        [Authorize(Roles = "Admin")]
        public ActionResult ImageDel(int id_img, int id_pro)
        {
            Image img = db.Images.Find(id_img);
            db.Images.Remove(img);
            db.SaveChanges();
            var image = db.Images.Where(i => i.ProductId == id_pro).OrderBy(i => i.Order);
            int k = 1;
            if (image.Count() > 0)
            {
                foreach (var item in image)
                {
                    item.Order = k;
                    db.Entry(item).State = EntityState.Modified;
                    k = k + 1;
                }
                db.SaveChanges();
            }
            

            return View();
        }

        [Authorize(Roles = "Admin")]
        public ActionResult ImageSort(int id_product, int id_image, int index_start, int index_end)
        {
            var image = db.Images.Find(id_image);
            if (index_start < index_end)
            {
                var arr_image1 = db.Images.Where(i => i.Order <= index_end && i.Order >= index_start && i.ProductId == id_product);
                foreach (var item1 in arr_image1)
                {
                    item1.Order = item1.Order - 1;
                    db.Entry(item1).State = EntityState.Modified;
                }
                image.Order = index_end;
            }else{
                if (index_start > index_end)
                {
                    var arr_image2 = db.Images.Where(i => i.Order <= index_start && i.Order >= index_end && i.ProductId == id_product);
                    foreach (var item2 in arr_image2)
                    {
                        item2.Order = item2.Order + 1;
                        db.Entry(item2).State = EntityState.Modified;
                    }
                    image.Order = index_end;
                }
            }
            db.SaveChanges();
            return RedirectToAction("products");
        }
/*************************************************************************
* Quan Ly Don Dat Hang
*************************************************************************/

        [Authorize(Roles = "Admin")]
        public ActionResult Orders(int? stt)
        {

            if (stt == null)
            {
                stt = 0;
            }
            var order = db.Orders.Where(o => o.Status == stt).OrderByDescending(a => a.OrderId);
            return View(order.ToList());           
        }

        [Authorize(Roles = "Admin")]
        public ActionResult OrderCount() 
        {
            int count = db.Orders.Where(o => o.Status == 0).Count();
            return Json(count);
        }

        [Authorize(Roles = "Admin")]
        public PartialViewResult autoreloadOrder(int? stt)
        {
            if (stt == null)
            {
                var order = db.Orders.Where(o => o.Status == 0).OrderByDescending(a => a.OrderId);
                return PartialView(order.ToList());
            }else{
                var order = db.Orders.Where(o => o.Status == stt).OrderByDescending(a => a.OrderId);
                return PartialView(order.ToList());
            }
        }

        [Authorize(Roles = "Admin")]
        public ActionResult OrderView(int id)
        {
            Order od = db.Orders.Find(id);
            ViewBag.order = od;

            var orderdetail = db.OrderDetails.Where(o => o.OrderId == id);

            if (orderdetail == null)
            {
                return HttpNotFound();
            }
            return View(orderdetail);
        }

        [Authorize(Roles = "Admin")]
        public ActionResult OrderActive(int id)
        {
            var find = db.Orders.Find(id);
            if (find.Status == 0)
            {
                find.Status = 1;
            }
            else
            {
                if (find.Status == 1) {
                    find.Status = 2;
                }
            }
            db.Entry(find).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("orders");
        }

        [Authorize(Roles = "Admin")]
        public ActionResult OrderDelete(int id)
        {
            var orderdetail = db.OrderDetails.Where(ot => ot.OrderId == id);
            foreach (var item in orderdetail)
            {
                db.OrderDetails.Remove(item); 
            }
            db.SaveChanges();
            Order order_del = db.Orders.Find(id);
            db.Orders.Remove(order_del);
            db.SaveChanges();
            return RedirectToAction("orders");
        }
/*************************************************************************
* Quan Ly Danh thu
*************************************************************************/
        [Authorize(Roles = "Admin")]
        public ActionResult statistic(string date)
        {
            //Xu ly tong danh thu
            ViewBag.total_statictis = db.Orders.Where(o => o.Status != 0).Sum(o => o.TotalPrice);
            DateTime time;// = Convert.ToDateTime(date);
            if (date == null)
	        {
		        time = DateTime.Now;
            }
            else time = Convert.ToDateTime(date);
            var order = db.Orders.Where(o => o.Status != 0 && o.CreateDate.Value.Day == time.Day && o.CreateDate.Value.Month == time.Month && o.CreateDate.Value.Year == time.Year).OrderByDescending(a => a.OrderId);
            ViewBag.total = db.Orders.Where(o => o.Status != 0 && o.CreateDate.Value.Day == time.Day && o.CreateDate.Value.Month == time.Month && o.CreateDate.Value.Year == time.Year).Sum(o => o.TotalPrice);
            return View(order.ToList()); 
        }

        [Authorize(Roles = "Admin")]
        public PartialViewResult reloadStatistic(string date, int stt)
        {
            DateTime time; 
            if (stt == 2)
            {
                time = Convert.ToDateTime("1/1/"+date);
            }
            else time = Convert.ToDateTime(date);
            var order = db.Orders.Where(o => o.Status != 0 && o.CreateDate.Value.Day == time.Day && o.CreateDate.Value.Month == time.Month && o.CreateDate.Value.Year == time.Year).OrderByDescending(a => a.OrderId);
            ViewBag.total = db.Orders.Where(o => o.Status != 0 && o.CreateDate.Value.Day == time.Day && o.CreateDate.Value.Month == time.Month && o.CreateDate.Value.Year == time.Year).Sum(o => o.TotalPrice);
            if (stt == 1)
            {
                order = db.Orders.Where(o => o.Status != 0 && o.CreateDate.Value.Month == time.Month && o.CreateDate.Value.Year == time.Year).OrderByDescending(a => a.OrderId);
                ViewBag.total = db.Orders.Where(o => o.Status != 0 && o.CreateDate.Value.Month == time.Month && o.CreateDate.Value.Year == time.Year).Sum(o => o.TotalPrice);
            }
            else if (stt == 2)
            {
                order = db.Orders.Where(o => o.Status != 0 && o.CreateDate.Value.Year == time.Year).OrderByDescending(a => a.OrderId);
                ViewBag.total = db.Orders.Where(o => o.Status != 0 && o.CreateDate.Value.Year == time.Year).Sum(o => o.TotalPrice);
            }
            
            return PartialView(order.ToList());
        }

        [Authorize(Roles = "Admin")]
        public ActionResult monthStatictis()
        {
            ViewBag.total_statictis = db.Orders.Where(o => o.Status != 0).Sum(o => o.TotalPrice);
            DateTime date = DateTime.Now;
            var order = db.Orders.Where(o => o.Status != 0 && o.CreateDate.Value.Month == date.Month && o.CreateDate.Value.Year == date.Year).OrderByDescending(a => a.OrderId);
            ViewBag.total = db.Orders.Where(o => o.Status != 0 && o.CreateDate.Value.Month == date.Month && o.CreateDate.Value.Year == date.Year).Sum(o => o.TotalPrice);
            return View(order.ToList());
        }

        [Authorize(Roles = "Admin")]
        public ActionResult yearStatictis()
        {
            ViewBag.total_statictis = db.Orders.Where(o => o.Status != 0).Sum(o => o.TotalPrice);
            DateTime date = DateTime.Now;
            var order = db.Orders.Where(o => o.Status != 0 &&o.CreateDate.Value.Year == date.Year).OrderByDescending(a => a.OrderId);
            ViewBag.total = db.Orders.Where(o => o.Status != 0 && o.CreateDate.Value.Year == date.Year).Sum(o => o.TotalPrice);
            return View(order.ToList());
        }
    }
}
